package ebcs.scan.interceptor;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import ebcs.database.bean.sys.PaUserRoleFunc;
import ebcs.scan.bean.sys.SysUserInfor;
import jplat.base.constant.KPlatResponseCode;
import jplat.core.session.redis.JRedisSession;
import jplat.core.trans.JAppConnectInfo;
import jplat.error.exception.JSystemException;
import jplat.tools.coder.JsonCoder;
import jplat.tools.config.JAppConfig;
import jplat.tools.config.JLogConfig;

/**
 * 用户权限拦截器
 * @author csd
 *
 */
public class UserFunctionInterceptor implements HandlerInterceptor{
	private Logger logger = Logger.getLogger(UserFunctionInterceptor.class);
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub
		
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
		
		if(JAppConfig.APP_FUNCTION_SWITCH==false) {
			return true;
		}
		//获取用户登录标识
		HttpSession session = request.getSession();
		HttpServletRequest req = (HttpServletRequest)request;
		String myUrl = req.getRequestURL().toString();
		logger.info("myUrl-->"+myUrl);
		//从Cookie中获取.
		Map reqInfoMap = new HashMap();
				Cookie[] cookies = request.getCookies();
				if ( cookies != null )
				{
					for ( int i = 0; i < cookies.length; ++i )
					{
						if( JLogConfig.canPrintNetInfo() )
						{
							logger.info("Cookie::"+cookies[i].getName()+"="+cookies[i].getValue());
						}
						
						reqInfoMap.put(cookies[i].getName(), cookies[i].getValue());
					}
				}
		JRedisSession redis =  new JRedisSession(String.valueOf(reqInfoMap.get("ttkn2")));
		SysUserInfor user = (SysUserInfor)redis.getUserInfo();
		for(PaUserRoleFunc func:user.getFuncList()) {
			if(myUrl.contains(func.getMenuUrl())) {
				return true;
			}
		}
		logger.info("request cookies:"+JsonCoder.toJsonString(user.getFuncList()));
		
		BufferedOutputStream outs = null;
		try
		{
			outs = new BufferedOutputStream(response.getOutputStream());
			Map retMap = new HashMap();
			Map headMap = new HashMap();
			Map bodyMap = new HashMap();
			headMap.put("retCode", "0009");
			headMap.put("retMsg", "该操作已经超出该用户的使用权限.");
			bodyMap.put("", "");
			retMap.put("head",headMap);//{"head":{"retCode":"0005","retMsg":"会话超时."},"body":""}
			retMap.put("body", bodyMap);
			String toApp = JsonCoder.toJsonString(retMap);
			//String toApp = JsonCoder.toJsonNoNullString(retMap);//将为null的字段转换为空
			logger.info("__TO_APP1:"+toApp);
			byte[] toData = toApp.getBytes("utf-8");
			outs.write(toData);
			response.setContentLength(toData.length);
			response.setContentType("application/json;charset=UTF-8");
			response.setHeader(JAppConnectInfo.H_RET_HEAD, JAppConnectInfo.V_HRETCODE_SUCC);
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
			throw new JSystemException(KPlatResponseCode.CD_WRITE_ERR,KPlatResponseCode.MSG_WRITE_ERR);
		}
		finally
		{
			if ( outs != null )
			{
				try {
					outs.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
		
		return false;
	}

	
}
